package com.utaedang.jesseclub;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import net.daum.mobilead.AdHttpListener;
import net.daum.mobilead.impl.animation.AnimationType;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.cauly.android.ad.AdInfo;
import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.utaedang.jesseclub.utils.DateUtil;
import com.utaedang.jesseclub.utils.Function;
import com.utaedang.jesseclub.utils.Function.AlarmWakeLock;
import com.utaedang.jesseclub.utils.GlobalContext;
import com.utaedang.jesseclub.utils.JesseclubDetailHTMLParse;

public class JesseclubDetailActivity extends Activity implements com.google.ads.AdListener, com.cauly.android.ad.AdListener, AdHttpListener {

	String HT_HEAD_S = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><html><head></head><body onload='JavaScript:scrollDown();' bgcolor='black'>";
	String HT_HEAD_SCR = "<SCRIPT language=\"JavaScript\"> function scrollDown(){window.scroll(0, document.body.offsetHeight); }</SCRIPT>";
	String HT_HEAD_E = "</body></html>";

	private static final String TAG = JesseclubDetailActivity.class.getSimpleName();
	
	private com.google.ads.AdView aAdView;
	private com.cauly.android.ad.AdView cAdView;
	private com.cauly.android.ad.AdInfo cAdInfo;
	private net.daum.mobilead.MobileAdView dAdView;
	private boolean isInterstitial;
	private Display display;
	private FrameLayout flayout;
	private LinearLayout glayout;
	
	private Timer mTimer = null;
	private String url;
	private String refresh_sc;
	private ProgressDialog dialog;
	private Activity activity;
	private boolean isRunning = true;
	private String content = "";
	private String oldContent = "";
	private WebView web;
	
	private JesseclubDetailHTMLParse hp;

	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// WebView 완료 시 처리;
			isRunning = false;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Title 변경 방법 1 순서 지킬 것
		Window window = getWindow();
		window.requestFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.jesseboard);
		window.setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar);

		activity = this;

		// Title 변경 방법 2
		// activity.setTitle(getResources().getString(R.string.app_title));

		dialog = new ProgressDialog(activity);
		
		LinearLayout layout = (LinearLayout) findViewById(R.id.layout); // 제일 바깥 LinearLayout, xml에서 weight="1" 줄것!
		flayout = new FrameLayout(this); // 중간의 FrameLayout
		GradientDrawable gradient = new GradientDrawable(
				GradientDrawable.Orientation.BOTTOM_TOP, new int[] {
						Color.BLACK, 0xff424242 }); // 그라데이션 생성
		flayout.setBackgroundDrawable(gradient);
		glayout = new LinearLayout(this); // 제일 안쪽 Gravity용 LinearLayout
		glayout.setGravity(0x11);
		glayout.setPadding(0, 3, 0, 3);
		ProgressBar progress = new ProgressBar(this); // ProgressBar 생성
		progress.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		// ProgressBar의 width, height를 레이아웃에 맞춤. 이 과정이 있어야 틀에 맞게 이쁘게 나옴..
		
		web = new WebView(this);
		web.setWebViewClient(new WebViewClient());
		web.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		web.getSettings().setJavaScriptEnabled(true); // 자바스크립트 허용
		web.getSettings().setSupportZoom(true); // Zoom 설정
		web.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		web.setBackgroundColor(Color.parseColor("#000000"));
		web.setVerticalScrollBarEnabled(false);
		web.setHorizontalScrollBarEnabled(false);
		
		glayout.addView(progress);
		flayout.addView(glayout);
		
		/*
		 * 광고 설정 부분 시작
		 * 카울리 -> 아담 -> 애드몹 순서
		 */
		//1.애드몹
		//AdmobCpcAd();

		//2.카울리
		//전면 광고 사용 시
	    /*
	    display = ((WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        
		int height = display.getHeight();
		int width = display.getWidth();
		int layout_height = 0;
		if (height > width) {
			layout_height = height / 10;
		} else {
			layout_height = width / 10;
		}
  		CaulyInterstitialAd();
  		*/
		//CPC 광고 사용 시
		CaulyCpcAd();
		
		//3.아담
		//AdamCpcAd();
		
		layout.addView(flayout);
		layout.addView(web);

		Intent intent = this.getIntent();
		url = intent.getStringExtra("url");

		if (url.equals("")) {
			Toast.makeText(getBaseContext(), "알 수 없는 URL입니다.",
					Toast.LENGTH_LONG).show();
			return;
		}
		if (!Function.IsWifiAvailable(getBaseContext())
				&& !Function.Is3GAvailable(getBaseContext())) {
			Toast.makeText(getBaseContext(), "네크워크에 연결할 수 없습니다.",
					Toast.LENGTH_LONG).show();
			return;
		}

		hp = new JesseclubDetailHTMLParse(activity, handler, web);
		hp.open(url);

		// WebView 환경 설정
		web.setWebChromeClient(new mWebChromeClient());
		web.setWebViewClient(new mWebViewClient());
	}

	//애드몹
	private void AdmobCpcAd(){
		aAdView = new com.google.ads.AdView(this, com.google.ads.AdSize.BANNER, GlobalContext.ADMOB_ID); // 애드몹 생성
		aAdView.setAdListener((com.google.ads.AdListener)this);
		aAdView.setBackgroundColor(Color.BLACK);
		com.google.ads.AdRequest request = new com.google.ads.AdRequest();
		aAdView.loadAd(request);
		
		flayout.addView(aAdView);
  	}
	
	//카울리 전면광고
  	private void CaulyInterstitialAd(){
  		//광고 정보 셋팅
  		cAdInfo = new com.cauly.android.ad.AdInfo();
  		cAdInfo.setPriority(Thread.NORM_PRIORITY); //Thread 우선 순위 (1 ~ 10) 
  		cAdInfo.initData(GlobalContext.CAURY_ID, "cpm", "all", "all", "off", "default", "yes", 0, false);
          
        //광고 View
        cAdView = new com.cauly.android.ad.AdView(this); 
  		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
  				LayoutParams.FILL_PARENT,
  				LayoutParams.FILL_PARENT);	
  		cAdView.setVisibility(View.VISIBLE);
  		cAdView.setAdListener((com.cauly.android.ad.AdListener) this);
  		cAdView.setLayoutParams(params);
  		//부모 레이아웃.
        flayout.addView(cAdView);
  		
  		isInterstitial = true;
  	}
  	
  	//카울리 CPC광고
  	private void CaulyCpcAd(){
  		//광고 정보 셋팅
  		cAdInfo = new com.cauly.android.ad.AdInfo();
		cAdInfo.setPriority(Thread.NORM_PRIORITY); //Thread 우선 순위 (1 ~ 10) 
        cAdInfo.initData(GlobalContext.CAURY_ID, "cpc", "all", "all", "off", "left_slide", "yes", 30, true);
          
        //광고 View
        cAdView = new com.cauly.android.ad.AdView(this); 
  		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
  				LayoutParams.FILL_PARENT,
  				LayoutParams.WRAP_CONTENT);	
  		//부모 레이어 하단에 위치할때.
	    //params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
  		//부모 레이어 상단에 위치할때.
	    params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
  		cAdView.setVisibility(View.VISIBLE);
  		cAdView.setAdListener((com.cauly.android.ad.AdListener) this);
  		cAdView.setLayoutParams(params);
  		
  		flayout.addView(cAdView);
  		
  		isInterstitial = false;
  	}
  	
  	//아담 CPC
  	private void AdamCpcAd(){
		// 할당 받은 clientId 설정
		net.daum.mobilead.AdConfig.setClientId(GlobalContext.ADAM_ID);
		
		// Ad@m 광고 뷰 생성 및 설정
		dAdView = new net.daum.mobilead.MobileAdView(this);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
  				LayoutParams.FILL_PARENT,
  				LayoutParams.WRAP_CONTENT);
		//부모 레이어 하단에 위치할때.
	    //params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
  		//부모 레이어 상단에 위치할때.
	    params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		// Animation 효과 : 기본 값은 AnimationType.NONE
		dAdView.setAnimationType(AnimationType.FLIP_VERTICAL);
		
		dAdView.setAdListener((net.daum.mobilead.AdHttpListener)this);
		dAdView.setVisibility(View.VISIBLE);

		flayout.addView(dAdView, params);

   	}
  	
	// HTML 제거
	public static String getConvData(String htmlData) {
		String return_val = htmlData.replaceAll("\\<.*?>", ""); // android.text.Html.fromHtml(htmlData).toString();
		return_val = return_val.trim();

		if (!return_val.equals("")) {
			if (return_val.substring(0, 1).equals("▶")) {
				if (return_val.indexOf("매수") > -1
						|| return_val.indexOf("돌파") > -1) {
					// notiTitle = "매수/돌파";
					return_val = "<font color='hotpink'>" + return_val
							+ "</font>";
				} else if (return_val.indexOf("매도") > -1
						|| return_val.indexOf("이탈") > -1) {
					return_val = "<font color='skyblue'>" + return_val
							+ "</font>";
					// notiTitle = "매도/이탈";
				} else {
					return_val = "";
				}
			} else {
				return_val = "";
			}
		} else {
			return_val = "";
		}
		return (return_val);
	}

	public void Notification(Context context) {
		AudioManager clsAudioManager = (AudioManager) context
				.getSystemService(Context.AUDIO_SERVICE);
		Vibrator clsVibrator = (Vibrator) context
				.getSystemService(Context.VIBRATOR_SERVICE);

		switch (clsAudioManager.getRingerMode()) {
		case AudioManager.RINGER_MODE_VIBRATE:
			// 진동 모드
			Log.d(TAG, "RINGER_MODE_VIBRATE");
			clsVibrator.vibrate(500);
			// clsVibrator.cancel();
			break;
		case AudioManager.RINGER_MODE_NORMAL:
			// 소리 모드
			Log.d(TAG, "RINGER_MODE_NORMAL");
			Ringtone alarmRingtone = RingtoneManager.getRingtone(context,
					RingtoneManager
							.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
			alarmRingtone.play();
			alarmRingtone.stop();
			break;
		case AudioManager.RINGER_MODE_SILENT:
			// 무음 모드
			Log.d(TAG, "RINGER_MODE_SILENT");
			break;
		}
	}

	private class mWebChromeClient extends WebChromeClient {
		public void onProgressChanged(WebView view, int progress) {
			super.onProgressChanged(view, progress);
			/*
			 * if (progress<100) { if(!dialog.isShowing()){
			 * dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			 * dialog.setMessage("데이터 로딩 중..."); dialog.setProgress(progress);
			 * dialog.setMax(100); dialog.show(); }else{
			 * dialog.setProgress(progress); } }else if (progress==100){
			 * if(dialog.isShowing()){ dialog.cancel(); } }
			 */
		}
	}

	private class mWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			view.loadUrl(url);
			return true;
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			Toast.makeText(activity, "새로 고침 되었습니다.", Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);

			switch (errorCode) {
			case ERROR_AUTHENTICATION:
				Toast.makeText(activity, "서버에서 사용자 인증 실패", Toast.LENGTH_SHORT)
						.show();
				break; // 서버에서 사용자 인증 실패
			case ERROR_BAD_URL:
				Toast.makeText(activity, "잘못된 URL입니다.", Toast.LENGTH_SHORT)
						.show();
				break; // 잘못된 URL
			case ERROR_CONNECT:
				Toast.makeText(activity, "서버로 연결 실패", Toast.LENGTH_SHORT)
						.show();
				break; // 서버로 연결 실패
			case ERROR_FAILED_SSL_HANDSHAKE:
				Toast.makeText(activity, "SSL handshake 수행 실패",
						Toast.LENGTH_SHORT).show();
				break; // SSL handshake 수행 실패
			case ERROR_FILE:
				Toast.makeText(activity, "일반 파일 오류", Toast.LENGTH_SHORT).show();
				break; // 일반 파일 오류
			case ERROR_FILE_NOT_FOUND:
				Toast.makeText(activity, "파일을 찾을 수 없습니다.", Toast.LENGTH_SHORT)
						.show();
				break; // 파일을 찾을 수 없습니다
			case ERROR_HOST_LOOKUP:
				Toast.makeText(activity, "서버 또는 프록시 호스트 이름 조회 실패",
						Toast.LENGTH_SHORT).show();
				break; // 서버 또는 프록시 호스트 이름 조회 실패
			case ERROR_IO:
				Toast.makeText(activity, "서버에서 읽거나 서버로 쓰기 실패",
						Toast.LENGTH_SHORT).show();
				break; // 서버에서 읽거나 서버로 쓰기 실패
			case ERROR_PROXY_AUTHENTICATION:
				Toast.makeText(activity, "프록시에서 사용자 인증 실패", Toast.LENGTH_SHORT)
						.show();
				break; // 프록시에서 사용자 인증 실패
			case ERROR_REDIRECT_LOOP:
				Toast.makeText(activity, "너무 많은 리다이렉션", Toast.LENGTH_SHORT)
						.show();
				break; // 너무 많은 리디렉션
			case ERROR_TIMEOUT:
				Toast.makeText(activity, "연결 시간 초과", Toast.LENGTH_SHORT).show();
				break; // 연결 시간 초과
			case ERROR_TOO_MANY_REQUESTS:
				Toast.makeText(activity, "페이지 로드중 너무 많은 요청 발생",
						Toast.LENGTH_SHORT).show();
				break; // 페이지 로드중 너무 많은 요청 발생
			case ERROR_UNKNOWN:
				Toast.makeText(activity, "일반 오류", Toast.LENGTH_SHORT).show();
				break; // 일반 오류
			case ERROR_UNSUPPORTED_AUTH_SCHEME:
				Toast.makeText(activity, "지원되지 않는 인증 체계", Toast.LENGTH_SHORT)
						.show();
				break; // 지원되지 않는 인증 체계
			case ERROR_UNSUPPORTED_SCHEME:
				Toast.makeText(activity, "URI가 지원되지 않는 방식", Toast.LENGTH_SHORT)
						.show();
				break; // URI가 지원되지 않는 방식
			}
		}
	}

	// Preference 값을 읽어와 보여주기 위해서.
	public void checkPreference() {
		// TODO Auto-generated method stub
		if (DateUtil.getDayOfTheWeek().equals("토")
				|| DateUtil.getDayOfTheWeek().equals("일")) {
			Toast.makeText(getBaseContext(), "주말에는 쉬세요~", Toast.LENGTH_LONG)
					.show();
		} else {
			if (!Prefs.getAutoRefresh(this).equals("NO")) {
				refresh_sc = Prefs.getAutoRefresh(this);
				String msg = Prefs.getAutoRefresh(this)
						+ "초 단위 자동 갱신 됩니다.\n메뉴/설정에서 변경하실 수 있습니다.";

				Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this,
						"자동 새로 고침 설정이 해제 되어 있습니다.\n메뉴/설정에서 변경하실 수 있습니다.",
						Toast.LENGTH_SHORT).show();
			}
		}

		// 항상 켜짐 유지
		if (Prefs.getDisplayOff(this)) {
			Log.d(TAG, "Screen On");
			getWindow()
					.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			AlarmWakeLock.wakeLock(getBaseContext());
		} else {
			Log.d(TAG, "Screen Off");
			getWindow().clearFlags(
					WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
			AlarmWakeLock.releaseWakeLock();
		}
	}

	@Override
	public void onDestroy() {
		if(aAdView != null)
			aAdView.destroy();
		if(dAdView != null)
			dAdView.destroy();
		cAdView.setVisibility(View.GONE);
		cAdView = null;
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		AlarmWakeLock.releaseWakeLock();
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (mTimer != null) {
			mTimer.cancel();
		}
		getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		AlarmWakeLock.releaseWakeLock();
		super.onPause();
	}

	// 현재 액티비티로 돌아오면 실행
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		checkPreference();
		if (!Prefs.getAutoRefresh(this).equals("NO")) {
			if (!DateUtil.getDayOfTheWeek().equals("토")
					&& !DateUtil.getDayOfTheWeek().equals("일")) {
				mTimer = new Timer();
				mTimer.schedule(new webTimer(),
						Long.parseLong(refresh_sc) * 1000,
						Long.parseLong(refresh_sc) * 1000);
			}
		}
	}

	// WebView 갱신 처리
	private class webTimer extends TimerTask {
		public void run() {
			handler.post(new Runnable() {
				public void run() {
					// Log.d(TAG, "새로고침 : "+isRunning);
					Calendar c = Calendar.getInstance();

					if (c.get(Calendar.HOUR_OF_DAY) < 9) {
						Toast.makeText(getBaseContext(), "장시작 전입니다.",
								Toast.LENGTH_LONG).show();
						isRunning = true;
					} else if (c.get(Calendar.HOUR_OF_DAY) > 15) {
						Toast.makeText(getBaseContext(), "장마감 되었습니다.",
								Toast.LENGTH_LONG).show();
						isRunning = true;
					}

					if (!isRunning) {
						isRunning = true;
						if (!Function.IsWifiAvailable(getBaseContext())
								&& !Function.Is3GAvailable(getBaseContext())) {
							Toast.makeText(getBaseContext(),
									"네크워크에 연결할 수 없습니다.", Toast.LENGTH_LONG)
									.show();
							return;
						}
						BufferedReader br = null;
						String line;
						URL nURL;
						try {
							nURL = new URL("http://www.jesseclub.com/bbs/"
									+ url);

							URLConnection uCon = nURL.openConnection();

							br = new BufferedReader(new InputStreamReader(uCon
									.getInputStream(), "euc-kr"));

							while ((line = br.readLine()) != null) {
								String rtn = getConvData(line);
								if (!rtn.equals("null") && !rtn.equals("")
										&& rtn != null) {
									content += rtn
											+ "<br><hr color='#ffffffff' size=1 noshade>";
									Log.d(TAG, rtn);
								}
							}

							if (!content.equals(oldContent)) {
								Log.d(TAG, "신규 내용 수신!!!");
								oldContent = content;
								Notification(getApplicationContext());
							}

							// Log.d(TAG,android.text.Html.fromHtml(rtn).toString());

							content = HT_HEAD_S + HT_HEAD_SCR
									+ "<font size=-1 color='white'>" + content
									+ "<p align='right'>"
									+ c.get(Calendar.HOUR_OF_DAY) + "시"
									+ c.get(Calendar.MINUTE) + "분"
									+ c.get(Calendar.SECOND) + "초</p></font>"
									+ HT_HEAD_E;

							// String result =
							// EncodingUtils.getString(content.getBytes(), 0,
							// content.getBytes().length, "utf-8");

							web.loadDataWithBaseURL(
									"",
									content.replaceAll("\\+", " ").replaceAll(
											"null", ""), "text/html", "UTF-8",
									"");
							content = "";
						} catch (Exception e) {
							// TODO Auto-generated catch block
							isRunning = false;
						} finally {
							isRunning = false;
							if (br != null)
								try {
									br.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
						}
					}
				}
			});
		}
	}

	// 옵션 메뉴 선택시
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.jessedtl_menu, menu);

		return true;
	}

	// 옵션 메뉴 아이템 선택시
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.settings:
			startActivity(new Intent(this, Prefs.class));
			// Toast.makeText(this, "설정 선택.", Toast.LENGTH_SHORT).show();
			break;
		default:
			Toast.makeText(this, "옵션 메뉴 디폴트입니다.", Toast.LENGTH_SHORT).show();
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	// AdMob : implements AdMob Event Listeners [START]
	public void onDismissScreen(Ad arg0) {
		Log.d(TAG, "onDismissScreen");
	}

	public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
		Log.d(TAG, "failed to receive ad (" + arg1 + ")");
	}

	public void onLeaveApplication(Ad arg0) {
		Log.d(TAG, "onLeaveApplication");
	}

	public void onPresentScreen(Ad arg0) {
		Log.d(TAG, "onPresentScreen");
	}

	public void onReceiveAd(Ad arg0) {
		Log.d(TAG, "onReceiveAd");
	}
	// AdMob : implements AdMob Event Handlers [END]

	// Cauly : implements Cauly Event Listeners [START]
	public void onCloseInterstitialAd() {
		// TODO Auto-generated method stub
		CaulyCpcAd();		
	}

	public void onFailedToReceiveAd(boolean arg0) {
		Log.d("onFailedToReceiveAd", ""+cAdView.getErrorCode());
		Log.d("onFailedToReceiveAd", ""+cAdView.getErrorMessage());
		
		/*
		 * 전면광고가 없거나 최소 요청 시간 미만시 cpc광고를 호출 
		 */
		if(cAdView.getErrorCode() == GlobalContext.CAULY_INTERSTITIAL_NO_FILLED_AD 
				|| cAdView.getErrorCode() == GlobalContext.CAULY_INTERSTITIAL_NOT_PERMITED) {
			Log.e("onFailedToReceiveAd", "전면광고 없음");
			CaulyCpcAd();
		} else {
			//타사 광고를 호출하거나 개발사 내부 광고를 호출
			flayout.removeAllViews();
			flayout.addView(dAdView);
		}
		
	}

	public void onReceiveAd() {
		Log.d("onReceiveAd", ""+cAdView.getErrorCode());

		if(cAdView.getErrorCode() == GlobalContext.CAULY_INVALID_APPCODE) {
			// 앱코드가 부정확하므로 확인이 필요합니다. 
			Log.e("onReceiveAd", "앱코드가 부정확하므로 확인이 필요합니다.");
		}
		
		if(!isInterstitial)
		{
			flayout.removeAllViews();
			//if(!cAdView.isChargeableAd()) {
				// 타사 광고를 호출하거나 개발사 내부 광고를 호출
				//flayout.addView(glayout);
				//flayout.addView(adView);
			//} else {
				flayout.addView(glayout);
				flayout.addView(cAdView);
			//}
			
		}
	}
	// Cauly : implements Cauly Event Listeners [END]
	
	// ad@m : implements Cauly Event Listeners [START]
	public void didDownloadAd_AdListener() {
		flayout.removeAllViews();
		AdamCpcAd();
	}

	public void failedDownloadAd_AdListener(int arg0, String arg1) {
		flayout.removeAllViews();
		AdmobCpcAd();	
	}
	// ad@m : implements Cauly Event Listeners [END]
}